﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace RedeSocial.ViewModels
{
	internal class Security
	{
		private static byte[] Key
		{
			get
			{
				byte[] retKey = Encoding.UTF8.GetBytes("DFFE1042D3354BED9EC3D3C92008439C");
				return retKey;
			}
		}

		private static byte[] IV
		{
			get
			{
				byte[] retIV = Encoding.UTF8.GetBytes("9C358D2E74F94DA7");
				return retIV;
			}
		}

		internal static string Encrypt(string str)
		{
			if (string.IsNullOrEmpty(str))
			{
				return str;
			}
			string encryptStr = null;
			byte[] stringArray = Encoding.UTF8.GetBytes(str);
			using (RijndaelManaged rmCrypto = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 })
			{
				try
				{
					rmCrypto.KeySize = Key.Length * 8;
				}
				catch
				{
				}
				try
				{
					rmCrypto.BlockSize = IV.Length * 8;
				}
				catch
				{
				}
				rmCrypto.Key = Key;
				rmCrypto.IV = IV;
				using (MemoryStream memStream = new MemoryStream())
				{
					using (CryptoStream cryptStream = new CryptoStream(memStream, rmCrypto.CreateEncryptor(), CryptoStreamMode.Write))
					{
						cryptStream.Write(stringArray, 0, stringArray.Length);
						cryptStream.FlushFinalBlock();
					}
					encryptStr = System.Convert.ToBase64String(memStream.ToArray());
					return encryptStr;
				}
			}
		}

		internal static string Decrypt(string str)
		{
			if (string.IsNullOrEmpty(str))
			{
				return str;
			}
			string decryptStr = null;
			byte[] stringArray = System.Convert.FromBase64String(str);
			using (RijndaelManaged rmCrypto = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 })
			{
				try
				{
					rmCrypto.KeySize = Key.Length * 8;
				}
				catch
				{
				}
				try
				{
					rmCrypto.BlockSize = IV.Length * 8;
				}
				catch
				{
				}
				rmCrypto.Key = Key;
				rmCrypto.IV = IV;
				using (MemoryStream memStream = new MemoryStream())
				{
					using (CryptoStream cryptStream = new CryptoStream(memStream, rmCrypto.CreateDecryptor(), CryptoStreamMode.Write))
					{
						cryptStream.Write(stringArray, 0, stringArray.Length);
						cryptStream.FlushFinalBlock(); cryptStream.Close();
					}
					decryptStr = Encoding.UTF8.GetString(memStream.ToArray());
					return decryptStr;
				}
			}
		}
	}
}
